package com.lyf.service.admin.impl;

import com.alibaba.fastjson.JSON;
import com.lyf.constant.MessageConstant;
import com.lyf.context.BaseContext;
import com.lyf.dto.*;
import com.lyf.exception.AddressBookBusinessException;
import com.lyf.exception.OrderBusinessException;
import com.lyf.exception.ShoppingCartBusinessException;
import com.lyf.mapper.admin.OrderDetailMapper;
import com.lyf.mapper.admin.OrderMapper;
import com.lyf.mapper.user.AddressBookMapper;
import com.lyf.mapper.user.ShoppingCartMapper;
import com.lyf.pojo.AddressBook;
import com.lyf.pojo.OrderDetail;
import com.lyf.pojo.Orders;
import com.lyf.pojo.ShoppingCart;
import com.lyf.result.PageResult;
import com.lyf.service.OrderService;
import com.lyf.vo.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lyf.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 订单取消
     * @param ordersCancelDTO
     */

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orderDB = orderMapper.getById(ordersCancelDTO.getId());
        if (orderDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        if (orderDB.getStatus() > Orders.TO_BE_CONFIRMED){
            throw new OrderBusinessException(MessageConstant.TRADE_STATUS_EXCEPTION);
        }
        if (orderDB.getStatus() == Orders.CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if (orderDB.getStatus() == Orders.TOBEDELIVERED){
            throw new OrderBusinessException(MessageConstant.ORDER_IS_DELIVERING_NO_CANCEL);
        }
        if (orderDB.getStatus() == Orders.TOBEPICKEDUP){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_TOBE_OUT);
        }
        Integer status = orderDB.getStatus() == Orders.PENDING_PAYMENT ? Orders.CANCELLED_ORDER : Orders.TO_BE_REFUND_ORDER;
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .status(status)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orderDB = orderMapper.getById(ordersConfirmDTO.getId());
        if (orderDB.getStatus() != Orders.TO_BE_CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orderDB = orderMapper.getById(ordersRejectionDTO.getId());
        if (orderDB.getStatus() != Orders.TO_BE_CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED_ORDER)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orderDB = orderMapper.getById(id);
        if (orderDB.getStatus() != Orders.CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.TOBEPICKEDUP)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orderDB = orderMapper.getById(id);
        if (orderDB.getStatus() != Orders.TOBEPICKEDUP){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETE_ORDER)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> orders = orderMapper.pageQuery(ordersPageQueryDTO);
        return new PageResult(orders.getTotal(),orders.getResult());
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = orderMapper.statistics();
        return orderStatisticsVO;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderDetailVO getOrderdetails(Long id) {
        // 查询订单基本信息
        OrderDetailVO orderDetailVO = orderMapper.getOrderById(id);
        if (orderDetailVO == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 查询订单详情列表
        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetailsByOrderId(id);
        
        // 设置订单详情列表
        orderDetailVO.setOrderDetailList(orderDetailList);
        
        // 构造订单菜品信息字符串
        StringBuilder orderDishesBuilder = new StringBuilder();
        for (OrderDetail orderDetail : orderDetailList) {
            orderDishesBuilder.append(orderDetail.getName())
                    .append("*")
                    .append(orderDetail.getNumber())
                    .append(";");
        }
        
        // 设置订单菜品信息
        if (orderDishesBuilder.length() > 0) {
            orderDetailVO.setOrderDishes(orderDishesBuilder.substring(0, orderDishesBuilder.length() - 1));
        }
        
        return orderDetailVO;
    }

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 异常情况处理（若地址信息为空，购物车数据为空）
        Long userId = BaseContext.getCurrentId();
        // 1. 查询地址信息
        AddressBook addressBook = AddressBook.builder()
                .id(ordersSubmitDTO.getAddressBookId())
                .build();
        List<AddressBook> addressBookList = addressBookMapper.list(addressBook);
        if (addressBookList == null || addressBookList.isEmpty()){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 2. 查询购物车数据
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(userId)
                .build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.isEmpty()){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 创建订单加入订单表
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        // 生成订单号（UUID生成）
        String orderNumber = UUID.randomUUID().toString();
        orders.setNumber(orderNumber);

        // 设置订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);

        // 设置下单用户 id
        orders.setUserId(userId);

        // 设置下单时间
        orders.setOrderTime(LocalDateTime.now());

        //  设置支付状态
        orders.setPayStatus(Orders.UN_PAID);

        // 设置用户名
        addressBook = addressBookList.get(0);
        orders.setUserName(addressBook.getConsignee());

        // 设置手机号
        orders.setPhone(addressBook.getPhone());

        // 设置收货地址
        String address = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        orders.setAddress(address);

        //设置收货人
        orders.setConsignee(addressBook.getConsignee());

        orderMapper.insert(orders);
        // 根据用户购物车信息将订单明细插入订单明细表
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);

        // 清空用户的购物车
        shoppingCartMapper.deleteById(shoppingCart);
        // 封装订单结果（OrderSubmitVO）并返回
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
        String OrderNumber = ordersPaymentDTO.getOrderNumber();

        paySuccess(OrderNumber);
        OrderPaymentVO orderPaymentVO =  OrderPaymentVO.builder()
                .nonceStr(LocalDateTime.now().toString())
                .paySign("lyf")
                .timeStamp(LocalDateTime.now().toString())
                .signType("MD5")
                .packageStr("PayConstants.PACKAGE_VALUE")
                .build();


        return orderPaymentVO;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);
        if (ordersDB.getStatus() == Orders.TO_BE_CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        // 通过WebSocket发送消息给商家客户端
        Map map = new HashMap();
        map.put("type", 1); // 1表示来单提醒，2表示客户催单提醒
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + outTradeNo);

        // 封装消息
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 历史订单查询
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult historyOrders(Integer page, Integer pageSize, Integer status) {
        PageHelper.startPage(page,pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO =  new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        Page<Orders> list = orderMapper.pageQuery(ordersPageQueryDTO);
        list.forEach(orders -> orders.setOrderDetailList(orderDetailMapper.getOrderDetailsByOrderId(orders.getId())));

        PageResult pageResult = PageResult.builder()
                .total(list.getTotal())
                .records(list.getResult())
                .build();
        return pageResult;
    }

    /**
     * 再来一单
     * @param id
     */
    @Transactional
    @Override
    public void repetition(Long id) {
        // 根据订单id查询订单数据
        Orders orders = orderMapper.getById(id);
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 根据订单id查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetailsByOrderId(id);
        // 判断订单详情是否为空
        if (orderDetailList == null || orderDetailList.isEmpty()) {
            return;
        }
        
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = ShoppingCart.builder()
                    .name(orderDetail.getName())
                    .image(orderDetail.getImage())
                    .userId(BaseContext.getCurrentId())
                    .dishId(orderDetail.getDishId())
                    .createTime(LocalDateTime.now())
                    .setmealId(orderDetail.getSetmealId())
                    .dishFlavor(orderDetail.getDishFlavor())
                    .number(orderDetail.getNumber())
                    .amount(orderDetail.getAmount())
                    .build();
            shoppingCartList.add(shoppingCart);
        }
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    @Override
    public void reminder(Long id) {
        // 通过id查询订单
        Orders order = orderMapper.getById(id);
        if (order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 判断订单状态
        if (order.getStatus() < Orders.TO_BE_CONFIRMED || order.getStatus() > Orders.TOBEDELIVERED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 通过WebSocket发送消息给客户端
        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号：" + order.getNumber());

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
}